package service.impl;

import dao.UserDAO;
import dao.impl.UserDAOImpl;
import pojo.UserDO;
import service.UserService;

import javax.swing.*;
import java.io.Serializable;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getByUsernameAndPwd(String name, String pwd) {
        return userDAO.getByUsernameAndPwd(name, pwd);
    }

    @Override
    public void saveMoney(int id, double blance) {
        UserDO user = userDAO.getById(id);
        user.setBalance(user.getBalance() + blance);
        userDAO.update(user);
    }

    @Override
    public void getMoney(int id, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getBalance() < blance) {
            throw new Exception("余额不足");
        }
        user.setBalance(user.getBalance() - blance);
        userDAO.update(user);
    }

    @Override
    public void transferMoney(int id, String name, double money) throws Exception {
        UserDO user = userDAO.getById(id);
        UserDO otherUser = userDAO.getByUsernameAndPwd(name);
        if (user.getAccount().equals(name)) {
            throw new Exception("不能给自己转账");
        }
        if (user.getBalance() < money) {
            throw new Exception("余额不足");
        }
        if (otherUser == null) {
            throw new Exception("查无此人");
        }
        user.setBalance(user.getBalance() - money);
        otherUser.setBalance(otherUser.getBalance() + money);
        userDAO.update(user);
        userDAO.update(otherUser);

    }

    @Override
    public void changePsw(int id, String psw, String newPsw) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getPsw().equals(psw)) {
            throw new Exception("与旧密码相同");
        }
        if (!psw.equals(newPsw)) {
            throw new Exception("两次输入的密码不同");
        }
        if (!psw.matches("^[0-9]{6}$")) {
            throw new Exception("输入的密码不符合要求");
        }
        user.setPsw(psw);
        userDAO.update(user);
    }
}
